<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use app\index\model\Member as Members;
use think\Db;

class Baction extends Controller
{
    private $grade_names =
        [0 => '会员',
            1 => '高级会员',
            2 => '销售顾问',
            3 => '业务经理',
            4 => '渠道总监',]
    ;
   /*
    *
    */
   public function login(){
       header('Access-Control-Allow-Origin', '＊');
       $mobile = Request::instance()->post('username');
       if (!$mobile) {
           return json(['code' => 200, 'msg' => '参数错误']);
       }

       $password = Request::instance()->post('password');

       if (!$password) {
           return json(['code' => 200, 'msg' => '参数错误']);
       }

       $userinfo = Db::name('member')->field('id,username,token,sex,create_time,password')->where('mobile', $mobile)->find();


       if (!$userinfo) {
           return json(['code' => 200, 'msg' => '用户不存在，请重新输入或注册']);
       }

       if ($userinfo['password'] === md5($password) || password_verify($password,$userinfo['password'])||md5(md5($password))===$userinfo['password']) {
           Db::name('member')->where(['id' => $userinfo['id']])->update(['token' => self::settoken()]);
           $userinfo = Db::name('member')->field('id,username,token,sex,create_time')->where('mobile', $mobile)->find();
           unset($userinfo['password']);
           return json(['code' => 100, 'msg' => '登录成功', 'data' => $userinfo]);
       } else {
           echo md5($password);
           return json(['code' => 200, 'msg' => '登录失败,密码错误']);
       }
   }

    public function checkLogin()
    {
        header('Access-Control-Allow-Origin', '＊');
        $token = Request::instance()->post('token');
        if (empty($token)) {
            return json(['code'=>200,'msg'=>'token 不存在,请重新登录']);
        } else {
            $userinfo = Db::name('member')->field('id,username,token,sex,create_time')->where(['token'=>$token])->find();
            if (empty($userinfo)) {
                return json(['code'=>200,'msg'=>'token 不存在,请重新登录']);
            }
        }
        if($userinfo){
            return json(['code'=>100,'msg'=>'获取成功','data'=>$userinfo]);
        }else{
            return json(['code'=>200]);
        }
    }

    //退出
    public function logout()
    {
        $token = Request::instance()->post('token');
        if ($token) {
            $result = Db::name('member')->where(['token'=>$token])->update(['token'=>'']);
            if ($result) {
                return json(['code'=>100,'msg'=>'退出成功']);
            } else {
                return json(['code'=>200,'msg'=>'退出失败']);
            }
        } else {
            return json(['code'=>200,'msg'=>'参数错误']);
        }

    }




    /*
     * 获取好友
     */
   public function getFriends(){
       $token = Request::instance()->post('token');
       $page = Request::instance()->post('page');
       if (!$token) {
           return json(['code'=>200,'msg'=>'参数错误！']);
       }
       $userinfo = $this->token($token);

       if(!$userinfo)
       {
           return json(['code'=>200,'msg'=>'token不存在！']);
       }

       $uid = $userinfo['id'];
       if(!isset($page)){
           $page = 1;
       }else{
           $page = $page;
       }

       $memberModel = Db::name('member');


       $map['parentid'] = $uid;
       $support = $memberModel
           ->field('username,mobile')
           ->where($map)
           ->page($page,6)
           ->select();

       $total = $memberModel->where(['parentid'=>$uid])->count('id');
       $countTotal = $total;
       $total = ceil( $total/6 );
       if($support){
           return json(['code'=>100,'data'=>$support,'msg'=>'获取成功','page'=>['num'=>$page,'total'=>$total,'count_total'=>$countTotal]]);
       }else{
           return json(['code'=>200,'msg'=>'暂无记录']);
       }
   }

   /*
    * 获取工资记录
    */
   public function getSalary(){
       $token = Request::instance()->post('token');
       $page = Request::instance()->post('page');
       if (!$token) {
           return json(['code'=>200,'msg'=>'参数错误！']);
       }
       $userinfo = $this->token($token);

       if(!$userinfo)
       {
           return json(['code'=>200,'msg'=>'token不存在！']);
       }
       $uid = $userinfo['id'];
       if(!isset($page)){
           $page = 1;
       }else{
           $page = $page;
       }

       $salarylist = Db::name('b_salary');


       $map['user_id'] = $uid;
       $support = $salarylist
           ->field('month,salary as money')
           ->where($map)
           ->page($page,6)
           ->select();

       $total = $salarylist->where(['user_id'=>$uid])->count('id');
       $countTotal = $total;
       $total = ceil( $total/6 );
       if($support){
           return json(['code'=>100,'data'=>$support,'msg'=>'获取成功','page'=>['num'=>$page,'total'=>$total,'count_total'=>$countTotal]]);
       }else{
           return json(['code'=>200,'msg'=>'暂无记录']);
       }
   }

   /*
    * 获取个人信息
    * grade_name\grade\money\oldmoney\id\username\yeji\ztmoney
    */
   public function getInfo(){
       $token = Request::instance()->post('token');
       if (!$token) {
           return json(['code'=>200,'msg'=>'参数错误！']);
       }
       $userinfo = $this->token($token);
       if ($userinfo) {
           $userinfo['money'] = $userinfo['score'] + $userinfo['ztscore']+$userinfo['oldscore'];
           $bgx=Db::name('b_gx');
           $ids=$bgx->where('parent_id',$userinfo['id'])->select();
           $bsup=Db::name('order');
           $idArr = array();
           foreach($ids as $key)
           {
               array_push($idArr,$key['user_id']);
           }
           $map['uid'] = array('in',$idArr);
           $year = date("Y");
           $month = date("m");
           $allday = date("t");
           $start_time =strtotime($year."-".$month."-1");
           $end_time =strtotime(date('Y-m-1',strtotime('next month')));
           $map['create_time'] = array('between', array($start_time,$end_time));
           $map['type']=1;
           $map['status']=2;
//           $map['project_id'] = array('neq',28);
           $map['project_id'] = ['not in',[28,31,45,52]];
           $ress=$bsup->where($map)->sum('money');
//            echo $bsup->getLastSql();
           if($ress){
               $userinfo['yeji']=$ress;
           }else{
               $userinfo['yeji']=0;
           }
       }
       if(!$userinfo)
       {
           return json(['code'=>200,'msg'=>'token不存在！']);
       }else{

           $userinfo['create_time'] = date('Y-m-d H:i',$userinfo['create_time']);
           $userinfo['role_name'] = $this->grade_names[$userinfo['role']];
           return json(['code'=>100,'data'=>$userinfo,'msg'=>'获取成功']);
       }


   }

    function GetRandStr($length){
        $str='0123456789';
        $len=strlen($str)-1;
        $randstr='';
        for($i=0;$i<$length;$i++){
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    public static function settoken()
    {
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

    //订单升级
    public function upgradesuport(){
        //获取未计算等级与支持金额的数据
        $supportModel = Db::table('tf_order');
        $supportList = $supportModel->where(['transport'=>0,'status'=>2,'type'=>1])->limit(0,100)->select();
        dump(count($supportList));
        if (!empty($supportList)) {
            foreach ($supportList as $key=>$value) {
                //添加直推金额到member表ztmoney
                if ($value['money']) {
                    $memberData = Db::table('tf_member')->where(['id'=>$value['uid']])->find();
                    Db::table('tf_member')->where(['id'=>$value['uid']])->setInc('score',$value['money']);
                    Db::table('tf_member')->where(['id'=>$value['uid']])->update(['is_upgrade'=>1]);
                    Db::table('tf_member')->where(['id'=>$memberData['parentId']])->setInc('ztscore',$value['money']);
                    Db::table('tf_member')->where(['id'=>$memberData['parentId']])->update(['is_upgrade'=>1]);
                    Db::table('tf_order')->where(['id'=>$value['id']])->update(['transport'=>1]);
                    $this->upgrade($value['create_time']);
                }
            }
        }
    }

    private $role = [
        0=>0,
        1=>3500,
        2=>150000,
        3=>300000
    ];

    //用户升级
    private function upgrade($time){
        $memberModel = Db::table('tf_member');
        $memberList = $memberModel->where(['is_upgrade'=>1])->limit(0,100)->select();
        if (!empty($memberList)) {
            foreach ($memberList as $key=>$val) {
                $money = $val['score'] + $val['ztscore'] + $val['oldscore'];
                if ($money<=$this->role[1] && $val['role']<1) {
                    Db::table('tf_member')->where(['id'=>$val['id']])->update(['is_upgrade'=>0,'role'=>1]);
                    $data['user_id'] = $val['id'];
                    $data['oldgrade'] = $val['role'];
                    $data['newgrade'] = 1;
                    $data['create_time'] = $time;
                    Db::table('tf_b_gradelog')->insert($data);
                } elseif ($money>=$this->role[1] && $money<$this->role[2] && $val['role']<2) {
                    Db::table('tf_member')->where(['id'=>$val['id']])->update(['is_upgrade'=>0,'role'=>2]);
                    $data['user_id'] = $val['id'];
                    $data['oldgrade'] = $val['role'];
                    $data['newgrade'] = 2;
                    $data['create_time'] = $time;
                    Db::table('tf_b_gradelog')->insert($data);
                } elseif ($money>=$this->role[2] && $money<$this->role[3] && $val['role']<3) {
                    Db::table('tf_member')->where(['id'=>$val['id']])->update(['is_upgrade'=>0,'role'=>3]);
                    $data['user_id'] = $val['id'];
                    $data['oldgrade'] = $val['role'];
                    $data['newgrade'] = 3;
                    $data['create_time'] = $time;
                    Db::table('tf_b_gradelog')->insert($data);
                } elseif ($money>=$this->role[3] && $val['role']<4) {
                    Db::table('tf_member')->where(['id'=>$val['id']])->update(['is_upgrade'=>0,'role'=>4]);
                    $data['user_id'] = $val['id'];
                    $data['oldgrade'] = $val['role'];
                    $data['newgrade'] = 4;
                    $data['create_time'] = $time;
                    Db::table('tf_b_gradelog')->insert($data);
                } else {
                    Db::table('tf_member')->where(['id'=>$val['id']])->update(['is_upgrade'=>0]);
                }
            }
        }
    }

    //获取当月总业绩
    public function gettyj($token){
//        $token = Request::instance()->post('token');
        $userinfo = $this->token($token);
        if(!$userinfo)
        {
            return json(['code'=>200,'msg'=>'token不存在！']);
        }
        $uid = $userinfo['id'];
        $bgx=Db::name('b_gx');
        $ids=$bgx->where('parent_id',$uid)->select();

        $bsup=Db::name('order');
        $idArr = array();
        foreach($ids as $key)
        {
            array_push($idArr,$key['user_id']);
        }
        $map['uid'] = array('in',$idArr);
        $ress=$bsup->where($map)->sum('money');
        echo $bsup->getLastSql();
        return $ress;
    }

    private function token($token){
        $memberModel = Db::name('member');
        if (!$token) {
            return false;
        } else {
//            $data = $memberModel->field('id,username,token,mobile,sex,create_time,grade,money,oldmoney,ztmoney')->where(['token'=>$token])->find();
            $data = $memberModel->field('id,username,token,mobile,sex,create_time,role,score,ztscore,oldscore')->where(['token'=>$token])->find();
            if (empty($data)) {
                return false;
            } else {
                unset($data['password']);
                return $data;
            }
        }
    }

    /*
   * 获取用户推荐关系
   */
    public function getgxx(){
        //查找所有没有在关系表中的uid
        $bm=Db::name('member');

        $res=$bm->alias('a')
            ->field('a.id,a.parentid')
            ->join('tf_b_gx b','a.id=b.user_id','left')
            ->where('b.user_id is null and a.parentid !=0')
            ->limit(20)
            ->select();
        foreach ($res as $k=>$v){
            $this->gx($v['id']);
        }
    }

    /*
     * 节点关系表
     *
     */

    public function gx($mid){
        set_time_limit(0);
        $gx=DB::name('b_gx');
        $member=Db::name('member');
        //判断是否已经有关系了
        $ingx=$gx->where('user_id',$mid)->find();
        if($ingx!=null){
            return null;
            die();
        }else{
        $data=array();
        $allfather=$this->getAllFather($mid);
        if($allfather==null){
            return null;
            die();
        }
        for($i=0;$i<sizeof($allfather);$i++){
            if($allfather[$i]['parent_id']==0){
                break;
            }
            $data[$i]['user_id']=$mid;
            $data[$i]['parent_id']=$allfather[$i]['parent_id'];
            $data[$i]['gx']=$i+1;
        }
//        dump($data);
//        die();
        $res=$gx->insertAll($data);
        if(!$res){
            return null;
        }
        echo $mid.'</br>';
//        $res2=$member->where('user_id',$mid)->update(['scgx'=>1]);
//        if(!$res2){
//            echo 123;
//            return null;
//        }
        // flush(); //这一部会使cache新增的内容被挤出去，显示到浏览器上
    }}

    public function getAllFather($mid,$arr=array()){
        if($mid==0&& $arr==null){
            return null;
            die();
        }elseif($mid<=0&& $arr!=null){
            return $arr;
            die();
        }
        else{
            $mres=$this->haveMid($mid);//获取mid数据
            if($mres==null){
                return null;
            }
            $data['user_id']=$mres['id'];
            $data['parent_id']=$mres['parentid'];
            $data['role']=$mres['role'];
            $arr[]=$data;
            return $this->getAllFather($data['parent_id'],$arr);
            die();        }
    }

    public function haveMid($mid){
        $member=Db::name('member');
        $mres=$member->field('id,parentid,role')->where('id',$mid)->find();
        if(!$mres){
            return null;
            die();
        }
        return $mres;
        die();
    }


}
